package code1.binary_tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 原题链接：https://leetcode.cn/problems/n-ary-tree-level-order-traversal/
 */
public class P429 {

    class Node {
        public int val;
        public List<Node> children;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    };

    //n叉树的层序遍历
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result=new ArrayList<>();
        Queue<Node> queue=new LinkedList<>();
        if(root==null){
            return result;
        }
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list=new ArrayList<>();
            for(int i=0;i<size;i++){
                Node node = queue.poll();
                list.add(node.val);
                node.children.stream().forEach(item->{
                    if(item!=null){
                        queue.offer(item);
                    }
                });
            }
            result.add(list);
        }
        return result;
    }
}
